package com.zzyl.nursing.service.impl;

import java.beans.Transient;
import java.time.LocalDateTime;
import java.util.List;

import com.alibaba.fastjson2.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.zzyl.common.utils.DateUtils;
import com.zzyl.nursing.domain.*;
import com.zzyl.nursing.dto.CheckInApplyDto;
import com.zzyl.nursing.dto.CheckInConfigDto;
import com.zzyl.nursing.dto.CheckInContractDto;
import com.zzyl.nursing.mapper.*;
import com.zzyl.nursing.util.CodeGenerator;
import org.apache.commons.lang3.ObjectUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.stereotype.Service;
import com.zzyl.nursing.service.ICheckInService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.PostMapping;
import springfox.documentation.spring.web.json.Json;

import java.util.Arrays;

/**
 * 入住信息表Service业务层处理
 *
 * @author ruoyi
 * @date 2025-07-25
 */
@Service
public class CheckInServiceImpl extends ServiceImpl<CheckInMapper, CheckIn> implements ICheckInService {
    @Autowired
    private CheckInMapper checkInMapper;

    @Autowired
    private ElderMapper elderMapper;

    @Autowired
    private BedMapper bedMapper;

    @Autowired
    private ContractMapper contractMapper;

    @Autowired
    private CheckInConfigMapper checkInConfigMapper;

    public CheckInServiceImpl() {
    }

    /**
     * 查询入住信息表
     *
     * @param id 入住信息表主键
     * @return 入住信息表
     */
    @Override
    public CheckIn selectCheckInById(Long id) {
        return getById(id);
    }

    /**
     * 查询入住信息表列表
     *
     * @param checkIn 入住信息表
     * @return 入住信息表
     */
    @Override
    public List<CheckIn> selectCheckInList(CheckIn checkIn) {
        return checkInMapper.selectCheckInList(checkIn);
    }

    /**
     * 新增入住信息表
     *
     * @param checkIn 入住信息表
     * @return 结果
     */
    @Override
    public int insertCheckIn(CheckIn checkIn) {
        return save(checkIn) ? 1 : 0;
    }

    /**
     * 修改入住信息表
     *
     * @param checkIn 入住信息表
     * @return 结果
     */
    @Override
    public int updateCheckIn(CheckIn checkIn) {
        return updateById(checkIn) ? 1 : 0;
    }

    /**
     * 批量删除入住信息表
     *
     * @param ids 需要删除的入住信息表主键
     * @return 结果
     */
    @Override
    public int deleteCheckInByIds(Long[] ids) {
        return removeByIds(Arrays.asList(ids)) ? 1 : 0;
    }

    /**
     * 删除入住信息表信息
     *
     * @param id 入住信息表主键
     * @return 结果
     */
    @Override
    public int deleteCheckInById(Long id) {
        return removeById(id) ? 1 : 0;
    }

    /**
     * 入住申请
     *
     * @param dto
     */
    @Override
    @Transactional
    public void apply(CheckInApplyDto dto) {
        //1.校验老人是否入住,查询老人是否存在
        LambdaQueryWrapper<Elder> queryWrapper = new LambdaQueryWrapper<>();
        // 根据身份证 参数 字段+值 判断状态为1
        queryWrapper.eq(Elder::getIdCardNo, dto.getCheckInElderDto().getIdCardNo())
                .eq(Elder::getStatus, 1);
        //查询老人信息,参数为wrapper条件
        Elder elder = elderMapper.selectOne(queryWrapper);
        //开始判断
        if (ObjectUtils.isNotEmpty(elder)) {
            throw new RuntimeException("该老人已入住");
        }
        //2.若未入住,更新床位状态为已入住,将前端的dto转换为床位对象并保存
        Bed bed = bedMapper.selectById(dto.getCheckInConfigDto().getBedId());
        //修改床位状态为开启
        bed.setBedStatus(1);

        bedMapper.updateById(bed);

        //3.新增或更新老人
        elder = insertOrUpdateElder(bed, dto);

        //4.新增签约合同办理
        insertOrUpdateContract(elder, dto);

        //5.新增入住信息
        CheckIn checkIn = insertCheckIn(elder, dto);

        //6.新增入住配置
        insertOrUpdateCheckInConfig(checkIn, dto);

    }

    private void insertOrUpdateCheckInConfig(CheckIn checkIn, CheckInApplyDto dto) {
        CheckInConfig checkInConfig = new CheckInConfig();
        //逻辑外键
        checkInConfig.setCheckInId(checkIn.getId());
        BeanUtils.copyProperties(dto.getCheckInConfigDto(), checkInConfig);

        //保存
        checkInConfigMapper.insert(checkInConfig);
    }

    private CheckIn insertCheckIn(Elder elder, CheckInApplyDto dto) {
        CheckIn checkIn = new CheckIn();
        checkIn.setElderId(elder.getId());
        checkIn.setIdCardNo(elder.getIdCardNo());
        checkIn.setElderName(elder.getName());
        checkIn.setBedNumber(elder.getBedNumber());
        checkIn.setStartDate(dto.getCheckInConfigDto().getStartDate());
        checkIn.setEndDate(dto.getCheckInConfigDto().getEndDate());
        checkIn.setStatus(0);
        checkIn.setNursingLevelName(dto.getCheckInConfigDto().getNursingLevelName());
        //7.保存老人家属信息为Json格式
        JSON.toJSONString(dto.getElderFamilyDtoList());
        checkIn.setRemark(JSON.toJSONString(dto.getElderFamilyDtoList()));
        checkInMapper.insert(checkIn);
        return checkIn;
    }

    private void insertOrUpdateContract(Elder elder, CheckInApplyDto dto) {
        Contract contract = new Contract();
        BeanUtils.copyProperties(dto.getCheckInContractDto(), contract);
        //添加合同关联老人id
        contract.setElderId(elder.getId());
        //生成合同编号
        contract.setContractNumber("HT" + CodeGenerator.generateContractNumber());
        contract.setElderName(elder.getName());

        //添加签约时间 从前端传递到checkInConfigDto拿值
        LocalDateTime startDate = dto.getCheckInConfigDto().getStartDate();
        LocalDateTime endDate = dto.getCheckInConfigDto().getEndDate();
        contract.setStartDate(startDate);
        contract.setEndDate(endDate);
        //判断合同状态,取当前时间判断是否生效 是1否0
        int status = startDate.isBefore(LocalDateTime.now()) ? 1 : 0;
        contract.setStatus(status);

        //保存合同信息
        contractMapper.insert(contract);
    }

    /**
     * 新增或更新老人信息
     */
    private Elder insertOrUpdateElder(Bed bed, CheckInApplyDto dto) {
        //创建新对象
        Elder e = new Elder();
        //将前端传来的值赋值给新对象
        BeanUtils.copyProperties(dto.getCheckInElderDto(), e);
        //将床位信息传递给老人,
        e.setBedNumber(bed.getBedNumber());
        //修改为1：入住中
        e.setStatus(1);
        //添加床位id
        e.setBedId(bed.getId());

        LambdaQueryWrapper<Elder> elderQueryWrapper = new LambdaQueryWrapper<>();
        elderQueryWrapper.eq(Elder::getIdCardNo, e.getIdCardNo())
                .eq(Elder::getStatus, 0);
        Elder elder = elderMapper.selectOne(elderQueryWrapper);
        //存在做更新，不存在做新增
        if (ObjectUtils.isEmpty(elder)) {
            elderMapper.insert(e);
        } else {
            e.setId(elder.getId());
            elderMapper.updateById(e);
        }

        return e;
    }

}
